<?php
/**
 * author: Administrator
 * <<<<<<< HEAD
 * createtime: 2015/9/28 21:21
 * description:
 * =======
 * Createtime: 2015/10/109:44
 * description:
 * >>>>>>> bea02473819e9dfd3a1527f269419d5eef4463dd
 */

namespace App\Http\Controllers;


use App\models\Permission;
use App\Models\Role;
use App\User;
use DB;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
use Zizaco\Entrust\Entrust;


class TestController extends Controller
{
    public function getIndex()
    {

        /* DB::insert('insert into users (id, name, email, password) VALUES (?,?,?,?)', ['1','Laravel','ajiader@1.com','123']);
         DB::insert('insert into users (id, name, email, password) VALUES (?,?,?,?)', ['2','Academy','academy@test.com','123']);*/
//        $users = DB::select('select * from users WHERE id = ?', ['1']);
//        $users = DB::select('select * from users WHERE id = :id', ['id'=>1]);
//        dd($users);
        /*        $affceted = DB::update('update users set name="LaravelAcademy" WHERE name = ?', ['Academy']);
                echo $affceted;*/
        /*        $deleted = DB::delete('delete from users');
                echo $deleted;*/
//        DB::statement('drop table users');
        /*        DB::insert('insert into users (id, name, email, password) values (?, ?, ? , ? )',
                    [4, 'LaravelAcademy2','laravel-academy@test2.com','1234']);*/
        // DB::transaction(function () {
        // DB::table('users')->update(['id' => 1]);
        //  DB::table('posts')->delete();

//        $posts = Post::all();
        /*$posts = Post::where('id','<','3')->orderBy('id','desc')->take(1)->get();
        dd($posts);*/
        /*Post::chunk(2, function($posts){
            foreach ($posts as $post) {
                echo $post->title.'<br>';
            }
        });*/
//        $post = Post::where('id','1')->first();
        /*$post = Post::findOrFail(1);
        dd($post);*/
        /* $count = Post::where('id','>','0')->count();
         echo $count;*/
        /* $views = Post::where('id','>','0')->max('views');
         echo $views;*/
        /*$post = new Post();
        $post->title = 'test 11';
        $post->content = 'text content';
        $post->user_id = 1;
        $post->cat_id = 1;
        if ($post->save()) {
            echo '添加文章成功！';
        } else {
            echo '添加文章失败！';
        }*/
        /*$input = [
            'title'=>'test 13',
            'content'=>'test content',
            'cat_id'=>1,
            'views'=>100,
            'user_id'=>2
        ];
        $post = Post::create($input);
        $post->user_id = 2;
        $post->views = 100;
        $post->save();
        dd($post);*/
        /*$post = Post::find(1);
        $post->title = 'test 1 title';
        if ($post->save()) {
            echo '更新文章成功！';
        }else{
            echo '更新文章失败！';
        }*/

        /*$input = [
            'title'=>'test 6 title',
            'content'=>'test content 6',
            'cat_id'=>1,
            'views'=>200,
            'user_id'=>1
        ];
        $post = Post::find(6);
        if ($post->update($input)) {
            echo '更新文章成功！';
            dd($post);
        } else {
            echo '更新文章失败！';
        }*/

        /*$post = Post::find(5);
        if ($post->delete()) {
            echo '删除成功！';
        } else {
            echo '删除文章失败！';
        }*/
        /*$deleted  = Post::destroy([6,7,8,9]);
        echo $deleted;*/
        /*$deleted = Post::where('views',0)->delete();
        echo $deleted;*/

        /*        $post = Post::find(2);
                $post->delete();
                if($post->trashed()){
                    echo '软删除成功！';
                    dd($post);
                }else{
                    echo '软删除失败！';
                }*/
        //只想要查看被软删除的模型
        /*$posts = Post::onlyTrashed()->get();
        dd($posts);*/
//        Post::withTrashed()->where('id','>',1)->restore();
//        Post::withTrashed()->restore();
        /*$post = Post::find(4);
        $post->forceDelete();*/

        //查询作用域
        /*$posts = Post::popular()->orderBy('views', 'desc')->get();
        foreach ($posts as $post) {
            echo '&lt;'.$post->title.'&gt; '.$post->views.'views<br>';
        }*/
        /*$posts = Post::popular()->status(1)->orderBy('views','desc')->get();
        foreach ($posts as $post) {
            echo '&lt;'.$post->title.'&gt; '.$post->views.'views<br>';
        }*/
        $data = array(
            'title' => 'test model event',
            'content' => 'test content',
            'cat_id' => 1,
        );
        $post = Post::create($data);
        if (!$post->exists) {
            echo '添加文章失败！';
            exit();
        }
        echo '&lt;' . $post->title . '&gt;保存成功！';
    }

    public function getSendmail()
    {
        \Mail::send('emails.welcome', ['key' => 'value'], function ($message) {
            $message->to('310255981@qq.com', 'John Smith')->subject('Welcome!');

        });
    }

    public function getRedis()
    {
        $key = 'user:name:5';

        $user = User::find(5);
        if ($user) {
            //将用户名存储到Redis中
            Redis::set($key, $user->name);
        }

//判断指定键是否存在
        if (Redis::exists($key)) {
            //根据键名获取键值
            dd(Redis::get($key));
        }
    }

    public function getRedis2()
    {
        $key = 'posts:title';

        $posts = Post::all();
        foreach ($posts as $post) {
//            echo $post->title;
            //将文章标题存放到集合中
            Redis::sadd($key, $post->title);
        }

        //获取集合元素总数(如果指定键不存在返回0)
        $nums = Redis::scard($key);
        dd(Redis::srandmember($key, 1));
        if ($nums > 0) {
            //从指定集合中随机获取三个标题
            $post_titles = Redis::smember($key, 1);
            dd($post_titles);
        }
    }

    public function getIndex2()
    {
        return \View::make('site.return');
    }

    public function getTest()
    {
        abort(403,'对不起，您无权访问该页面！');
    }

    public function getLog(){
/*        Log::emergency("系统挂掉了");
        Log::alert("数据库访问异常");
        Log::critical("系统出现未知错误");
        Log::error("指定变量不存在");
        Log::warning("该方法已经被废弃");
        Log::notice("用户在异地登录");
        Log::info("用户xxx登录成功");
        Log::debug("调试信息");*/
        Log::info("用户xxx登录成功",['user_id'=>1]);
    }

    public function postFileupload(Request $request)
    {
        header("Content-Type: text/html; charset=UTF-8") ;
        //判断请求中是否包含name=file的上传文件
        if(!$request->hasFile('file')){
            exit('上传文件为空！');
        }
        $file = $request->file('file');
        //判断文件上传过程中是否出错
        if(!$file->isValid()){
            exit('文件上传出错！');
        }
        $newFileName = md5(time().rand(0,10000)).'.'.$file->getClientOriginalExtension();
        $savePath = 'test/'.$newFileName;
        $bytes = Storage::put(
            $savePath,
            file_get_contents($file->getRealPath())
        );
        if (!Storage::exists($savePath)) {
            exit('保存文件失败！');
        }
        header("Content-Type:".\Storage::mimeType($savePath));
        echo Storage::get($savePath);
    }

    public function getFile()
    {
        $dirPath = 'test/abc';
        Storage::deleteDirectory($dirPath);
        $directories = Storage::directories('test');
        dd($directories);
    }
    
    public function getFileupload()
    {
        $csrf_field = csrf_field();
        $html = <<<UPDATE
        <form action="" method="POST" enctype="multipart/form-data">
            $csrf_field
            <input type="file" name="file"/>

            <input type="submit" value="提交"/>
        </form>
UPDATE;
        return $html;
    }

    public function getDeletefile()
    {
        $filePath = 'test/bfed97ce1246b2f94385010d6cb0887d.png';
        if(Storage::delete($filePath)){
            exit('删除成功！');
        }else{
            exit('删除失败！');
        }

    }

    public function getSession(Request $request)
    {
        $request->session()->push('site.xxx', 'http://LaravelAcademy.org');
        $request->session()->push('site.xxx', 'Laravel学院');
        if($request->session()->has('site')){
            $site = $request->session()->get('site');
            dd($site);
        }
    }

    public function getRole()
    {
        /*$owner = new Role();
        $owner->name            =  'owner';
        $owner->display_name    =  'Project Owner';
        $owner->description     =  'User is the owner of a given project';
        $owner->save();

        $admin = new Role();
        $admin->name         = 'admin';
        $admin->display_name = 'User Administrator'; // optional
        $admin->description  = 'User is allowed to manage and edit other users'; // optional
        $admin->save();*/
        $user = \App\models\User::where('name', '=', 'admin')->first();
        dd($user->ability(array('admin', 'owner'), array('create-post', 'edit-user')));
/*        $admin = Role::where('name', '=', 'admin')->first();
        $owner= Role::where('name', '=', 'owner')->first();*/
//        $user->attachRole($admin);
//        $user->roles()->attach($admin->id);

       /* $createPost = new Permission();
        $createPost->name     =   'Create-post';
        $createPost->display_name = 'Create Posts'; // optional
        // Allow a user to...
        $createPost->description  = 'create new blog posts'; // optional
        $createPost->save();

        $editUser = new Permission();
        $editUser->name         = 'edit-user';
        $editUser->display_name = 'Edit Users'; // optional
// Allow a user to...
        $editUser->description  = 'edit existing users'; // optional
        $editUser->save();*/
      /*  $createPost = Permission::where('name', '=', 'Create-post')->first();
        $editUser= Permission::where('name', '=', 'edit-user')->first();
        $admin->attachPermission($createPost);*/
// equivalent to $admin->perms()->sync(array($createPost->id));

      //  $owner->attachPermissions(array($createPost, $editUser));
// equivalent to $owner->perms()->sync(array($createPost->id, $editUser->id));
    }
}